from collections import OrderedDict
import yaml


def ordered_yaml_load(yaml_path, Loader=yaml.Loader,
                      object_pairs_hook=OrderedDict):
    class OrderedLoader(Loader):
        pass

    def construct_mapping(loader, node):
        loader.flatten_mapping(node)
        return object_pairs_hook(loader.construct_pairs(node))

    OrderedLoader.add_constructor(
        yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
        construct_mapping)

    with open(yaml_path) as stream:
        return yaml.load(stream, OrderedLoader)


def ordered_yaml_dump(data, stream=None, Dumper=yaml.SafeDumper, **kwds):
    class OrderedDumper(Dumper):
        pass

    def _dict_representer(dumper, data):
        return dumper.represent_mapping(
            yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
            data.items())

    OrderedDumper.add_representer(OrderedDict, _dict_representer)

    return yaml.dump(data, stream, OrderedDumper, **kwds)


if __name__ == "__main__":
    dumpfile = open('dump.yml', 'w', encoding='utf-8')

    pydir = {}
    cdir = OrderedDict()
    pydir['testcases'] = cdir
    cdir['rep1'] = 1
    cdir['csd2'] = 2
    cdir['fs3'] = 3
    cdir['你好asd4'] = 4
    cdir['ioweq5'] = 5
    cdir['asd6'] = 6
    res = ordered_yaml_dump(pydir, dumpfile, indent=4, default_flow_style=False, encoding='utf-8', allow_unicode=True)